package com.lnb.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.lnb.common.constant.BaseConstant;
import com.lnb.common.enums.PlatFormEnum;
import com.lnb.common.model.TokenBaseInfo;
import com.lnb.gateway.constant.Constant;
import com.lnb.gateway.util.ExchangeUtils;
import com.lnb.redis.utils.RedisUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>
 *
 * </p>
 *
 * @author liaoningbo
 * @since 2024-01-08
 */
@Component
@Log4j2
public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断是否跳过当前校验
        if (ExchangeUtils.isSkip(exchange)) {
            return chain.filter(exchange);
        }
        log.info("开始token验证");
        // 获取原始请求头
        HttpHeaders headers = exchange.getRequest().getHeaders();


        String token = headers.getFirst(BaseConstant.TOKEN);
        if (StrUtil.isEmpty(token)) {
            log.error("无token，请求结束，token：{}", token);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //验证token
        boolean flag = false;
        String platForm = headers.getFirst(BaseConstant.PLATFORM);
        try{
            if(StrUtil.isEmpty(platForm)){
                flag = JWTUtil.verify(token, BaseConstant.TOKEN_KEY.getBytes());
            }else{
                if(PlatFormEnum.SUPER.getPlatform().equals(platForm)){
                    flag = JWTUtil.verify(token, BaseConstant.SUPER_TOKEN_KEY.getBytes());
                }
            }
        }catch (Exception e){
            flag  =  false;
            log.error("e:{}",e);
        }
        if(!flag){
            log.error("token验证不通过，请求结束，token：{}", token);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }else{
            JWT jwt = JWTUtil.parseToken(token);
            TokenBaseInfo tokenBaseInfo = JSONUtil.toBean(String.valueOf(jwt.getPayload(BaseConstant.TOKEN_BEAN)), TokenBaseInfo.class);
            Long adminUserId = tokenBaseInfo.getAdminUserId();
            if(PlatFormEnum.SUPER.getPlatform().equals(platForm)){
                if(!RedisUtils.hasKey("slq:user:login:code:token:" + adminUserId)){
                    log.error("token失效，用户id：{}", adminUserId);
                    exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                    return exchange.getResponse().setComplete();
                }
            }else{
                if(!RedisUtils.hasKey("slq:user:login:token:" + adminUserId)){
                    log.error("token失效，用户id：{}", adminUserId);
                    exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                    return exchange.getResponse().setComplete();
                }
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Constant.TOKEN_FILTER_ORDER;
    }
}
